<template>
  <div class="ruleSetDetail">
    <el-drawer
      title="我是标题"
      :visible.sync="drawerVisible"
      size="70%"
      :with-header="false"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :before-close="cancelForm"
    >
      <div class="drawerForm">
        <div class="pageTitle">
          <div class="titleText">{{ formData.ruleSetName }}规则集</div>
          <slot name="header" />
        </div>
        <div class="formScrollbar">
          <el-form ref="formData" class="formContent" :model="formData" label-width="96px" label-suffix="：">
            <el-row class="ruleSetInfo">
              <el-col :span="12">
                <el-form-item label="ID编码" prop="ruleSetId">
                  <span v-if="drawerType !== 'copy'" class="fontBold">{{ formData.ruleSetId }}</span>
                </el-form-item>
                <el-form-item v-if="type === 'file'" label="变量库" prop="parameterModuleIdList">
                  <el-cascader
                    v-if="drawerType !== 'view'"
                    v-model="formData.parameterModuleIdList"
                    :disabled="drawerType === 'view2'"
                    :options="variableModelOption"
                    :props="{ multiple: true, emitPath: false }"
                    :show-all-levels="false"
                    clearable
                    class="w360"
                    collapse-tags
                  ></el-cascader>
                  <el-cascader
                    v-else
                    v-model="formData.parameterModuleIdList"
                    popper-class="cascaderView"
                    :options="formData.variableModelOptionList"
                    :props="{ multiple: true, emitPath: false }"
                    :show-all-levels="false"
                    class="w360 cascaderView"
                    collapse-tags
                  ></el-cascader>
                  <el-button
                    v-if="drawerType !== 'view'"
                    v-show="drawerType !== 'view2'"
                    type="primary"
                    class="carryBtn"
                    @click="handleClick('add')"
                  >
                    添加规则
                  </el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规则集名称" prop="ruleSetName">
                  <el-input
                    v-if="drawerType === 'copy'"
                    v-model="formData.ruleSetName"
                    class="w360 show-word-limit"
                    maxlength="20"
                    show-word-limit
                  />
                  <span v-else class="fontBold">{{ formData.ruleSetName }}规则集</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-scrollbar class="ruleContent">
              <transition-group name="el-zoom-in-top">
                <div v-for="(item, index) in formData.ruleDataList" :key="item.propId" class="ruleItem">
                  <el-form
                    :ref="'formRuleData' + index"
                    :rules="formRuleRules"
                    :model="item"
                    label-width="96px"
                    label-suffix="："
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="规则名称" prop="ruleName">
                          <el-input
                            v-if="drawerType !== 'view'"
                            v-model="item.ruleName"
                            :disabled="drawerType === 'view2'"
                            class="w360 show-word-limit"
                            maxlength="50"
                            show-word-limit
                            placeholder="请输入规则名称"
                          />
                          <span v-else class="fontBold">{{ item.ruleName }}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="规则备注" prop="ruleRemark">
                          <el-input
                            v-if="drawerType !== 'view'"
                            v-model="item.ruleRemark"
                            :disabled="drawerType === 'view2'"
                            class="w360 show-word-limit-52"
                            maxlength="255"
                            show-word-limit
                            placeholder="请输入规则备注"
                          />
                          <span v-else class="fontBold">{{ item.ruleRemark }}</span>
                          <el-popconfirm
                            title="其他规则前置规则引用了本条规则的话，其前置规则将被置空，确定删除吗？"
                            @confirm="handleClick('del', index)"
                          >
                            <el-button
                              v-if="drawerType !== 'view'"
                              v-show="drawerType !== 'view2'"
                              slot="reference"
                              class="carryBtn"
                            >
                              删除规则
                            </el-button>
                          </el-popconfirm>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row class="ruleBottom">
                      <el-col :span="12">
                        <el-form-item label="前置规则" prop="prepositionRuleData">
                          <el-select
                            v-if="drawerType !== 'view'"
                            v-model="item.prepositionRuleData.propId"
                            :disabled="drawerType === 'view2'"
                            clearable
                            class="w360"
                            @change="(val) => handleChangePrepositionRule(val, index)"
                          >
                            <el-option
                              v-for="row in prepositionRuleList.filter((row) => {
                                return (
                                  row.propId != item.propId &&
                                  !getPrepositionRuleArr(item.propId, []).includes(row.propId)
                                )
                              })"
                              :key="row.propId"
                              :label="row.label"
                              :value="row.propId"
                            ></el-option>
                          </el-select>
                          <span v-else class="fontBold">{{ item.prepositionRuleName }}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="条件关系" prop="conditionalRelation">
                          <el-select
                            v-if="drawerType !== 'view'"
                            v-model="item.conditionalRelation"
                            :disabled="drawerType === 'view2'"
                            clearable
                            class="w360"
                          >
                            <el-option
                              v-for="row in conditionalRelationOption"
                              :key="row.value"
                              :label="row.label"
                              :value="row.value"
                            ></el-option>
                          </el-select>
                          <span v-else class="fontBold">{{ item.conditionalRelationName }}</span>
                        </el-form-item>
                      </el-col>
                      <el-table :data="item.conditionDataList" class="conditionTable">
                        <el-table-column
                          type="index"
                          width="100"
                          label="条件序号"
                          align="center"
                        ></el-table-column>
                        <el-table-column v-if="type === 'file'" prop="description" label="条件描述" width="300">
                          <template slot-scope="scope">
                            <el-input
                              v-if="drawerType !== 'view' && drawerType !== 'view2'"
                              v-model="scope.row.description"
                              class="show-word-limit-52"
                              maxlength="255"
                              show-word-limit
                              placeholder="请输入条件描述"
                            />
                            <template v-else>{{ scope.row.description }}</template>
                          </template>
                        </el-table-column>
                        <el-table-column prop="conditionContent" label="条件内容">
                          <template slot-scope="scope">
                            <template v-if="type === 'parameterConfigure'">
                              <div class="conditionContent">
                                <el-input
                                  v-model="scope.row.factModeName"
                                  class="conditionInput"
                                  :disabled="drawerType === 'view' || drawerType === 'view2'"
                                  placeholder="请输入事实方式"
                                />
                                <el-input
                                  v-model="scope.row.comparator"
                                  class="conditionInput"
                                  :disabled="drawerType === 'view' || drawerType === 'view2'"
                                  placeholder="请输入比较符"
                                />
                                <el-input
                                  v-model="scope.row.standardSpecification"
                                  class="conditionInput"
                                  :disabled="drawerType === 'view' || drawerType === 'view2'"
                                  placeholder="请输入标准规范"
                                />
                              </div>
                            </template>
                            <template v-else>
                              <div v-if="drawerType !== 'view' && drawerType !== 'view2'" class="conditionContent">
                                <el-cascader
                                  v-model="scope.row.factMode"
                                  :options="factModeOption"
                                  :props="{ checkStrictly: true }"
                                  clearable
                                  popper-class="checkStrictlyPopper"
                                  style="width: 280px; margin-right: 10px"
                                  placeholder="请选择事实方式"
                                  @change="(val) => handleChangeFactMode(val, index, scope.$index)"
                                >
                                  <template slot-scope="{ data }">
                                    <span
                                      v-if="
                                        !data.children &&
                                        (data.type !== ConditionalType.valueData ||
                                          data.type !== ConditionalType.parameterType ||
                                          data.type !== ConditionalType.moduleData) &&
                                        data.isCanSelect
                                      "
                                    >
                                      {{ data.label }}
                                    </span>
                                    <span
                                      v-else
                                      :class="{
                                        hiddenPrefixIcon:
                                          ![
                                            ConditionalType.valueData,
                                            ConditionalType.parameterType,
                                            ConditionalType.moduleData
                                          ].includes(data.type) ||
                                          (data.type === ConditionalType.valueData && !data.isCanSelect)
                                      }"
                                    >
                                      {{ data.label }}
                                    </span>
                                  </template>
                                </el-cascader>
                                <el-select
                                  v-model="scope.row.comparator"
                                  style="width: 140px; margin-right: 10px"
                                  clearable
                                  placeholder="请选择比较符"
                                  @change="(val) => handleChangeComparator(val, index, scope.$index)"
                                >
                                  <el-option
                                    v-for="row in factModeToComparatorOption[scope.row.nearestFactMode] ?? []"
                                    :key="index + '_' + scope.$index + '_' + row.value"
                                    :label="row.label"
                                    :value="row.value"
                                  ></el-option>
                                </el-select>
                                <div style="width: 280px; display: flex">
                                  <!-- [1, 2, 3].includes(scope.row.comparator)
                                    ? 'standardSpecification checkStrictlyPopper'
                                    : 'checkStrictlyPopper' -->
                                  <el-cascader
                                    v-model="scope.row.standardSpecification"
                                    popper-class="
                                  checkStrictlyPopper
                                "
                                    :options="
                                      getStandardSpecification(
                                        standardSpecificationOption[
                                          scope.row.nearestFactMode + '-' + scope.row.comparator
                                        ] ?? [],
                                        scope.row.standardSpecification,
                                        scope.row.comparator,
                                        scope.row.visible
                                      )
                                    "
                                    :props="{
                                      multiple: [1, 2, 3].includes(scope.row.comparator),
                                      checkStrictly: true
                                    }"
                                    :show-all-levels="false"
                                    clearable
                                    style="width: 100%"
                                    collapse-tags
                                    placeholder="请选择标准规范"
                                    @visible-change="
                                      (value) => {
                                        scope.row.visible = value
                                      }
                                    "
                                  >
                                    <template slot-scope="{ data }">
                                      <span v-if="!data.children && data.type !== ConditionalType.valueData">
                                        {{ data.label }}
                                      </span>
                                      <span
                                        v-else
                                        :class="{ hiddenPrefixIcon: data.type !== ConditionalType.valueData }"
                                      >
                                        {{ data.label }}
                                      </span>
                                    </template>
                                  </el-cascader>
                                  <el-input
                                    v-if="scope.row.standardSpecification?.[0] === 1004"
                                    v-model="scope.row.enterValue"
                                    style="margin-left: 10px"
                                  />
                                </div>
                              </div>
                              <div v-else-if="drawerType === 'view2'" class="conditionContent">
                                <el-cascader
                                  v-model="conditionContents[scope.row.conditionId]"
                                  :options="getValueOption(scope.row.factMode, scope.row.conditionId)"
                                  popper-class="cascaderView"
                                  style="width: 380px; margin-right: 10px"
                                  class="cascaderView"
                                ></el-cascader>
                                <span class="comparatorContent">
                                  {{ scope.row.factMode.label }}
                                </span>
                                <el-select v-model="scope.row.comparator" style="width: 140px; margin-right: 40px">
                                  <el-option
                                    v-for="row in factModeToComparatorOption[scope.row.nearestFactMode] ?? []"
                                    :key="index + '_' + scope.$index + '_' + row.value"
                                    :label="row.label"
                                    :value="row.value"
                                  ></el-option>
                                </el-select>
                                <div style="width: 280px; display: flex">
                                  <!-- [1, 2, 3].includes(scope.row.comparator)
                                    ? 'standardSpecification checkStrictlyPopper'
                                    : 'checkStrictlyPopper' -->
                                  <el-cascader
                                    v-model="scope.row.standardSpecification"
                                    popper-class="
                                  checkStrictlyPopper
                                "
                                    :options="
                                      getStandardSpecification(
                                        standardSpecificationOption[
                                          scope.row.nearestFactMode + '-' + scope.row.comparator
                                        ] ?? [],
                                        scope.row.standardSpecification,
                                        scope.row.comparator,
                                        scope.row.visible
                                      )
                                    "
                                    :props="{
                                      multiple: [1, 2, 3].includes(scope.row.comparator),
                                      checkStrictly: true
                                    }"
                                    :show-all-levels="false"
                                    :disabled="true"
                                  >
                                    <template slot-scope="{ data }">
                                      <span v-if="!data.children && data.type !== ConditionalType.valueData">
                                        {{ data.label }}
                                      </span>
                                      <span
                                        v-else
                                        :class="{ hiddenPrefixIcon: data.type !== ConditionalType.valueData }"
                                      >
                                        {{ data.label }}
                                      </span>
                                    </template>
                                  </el-cascader>
                                  <el-input
                                    v-if="scope.row.standardSpecification?.[0] === 1004"
                                    v-model="scope.row.enterValue"
                                    style="margin-left: 10px"
                                  />
                                </div>
                              </div>
                              <div v-else class="conditionContent">
                                <el-cascader
                                  v-model="scope.row.factMode"
                                  popper-class="cascaderView"
                                  :options="scope.row.factModeOptionDataList"
                                  style="flex: 1; margin-right: 10px"
                                  class="cascaderView"
                                ></el-cascader>
                                <span class="comparatorContent">
                                  {{ scope.row.comparatorOptionDataList[0].label }}
                                </span>
                                <div style="flex: 1; display: flex">
                                  <el-cascader
                                    v-model="scope.row.standardSpecification"
                                    popper-class="cascaderView"
                                    :options="scope.row.standardSpecificationOptionDataList"
                                    :props="{ multiple: [1, 2, 3].includes(scope.row.comparator) }"
                                    :show-all-levels="false"
                                    class="cascaderView"
                                    style="flex: 1"
                                    collapse-tag
                                    placeholder="请选择标准规范"
                                  ></el-cascader>
                                  <el-input
                                    v-if="scope.row.standardSpecification?.[0] === 1004"
                                    v-model="scope.row.enterValue"
                                    readonly
                                    style="margin-left: 10px; flex: 1"
                                  />
                                </div>
                              </div>
                            </template>
                          </template>
                        </el-table-column>
                        <el-table-column v-if="drawerType !== 'view'" fixed="right" label="操作" width="160">
                          <template slot-scope="scope">
                            <el-popconfirm
                              title="确定删除吗？"
                              @confirm="handleClick('conditionDel', index, scope.$index)"
                            >
                              <el-link
                                v-show="drawerType !== 'view2'"
                                slot="reference"
                                class="conditionDel"
                                type="primary"
                                :underline="false"
                              >
                                删除
                              </el-link>
                            </el-popconfirm>

                            <el-link
                              v-show="drawerType !== 'view2'"
                              type="primary"
                              :underline="false"
                              @click.native.prevent="handleClick('conditionCopy', index, scope.$index)"
                            >
                              复制
                            </el-link>
                            <el-link
                              v-show="drawerType !== 'view2'"
                              type="primary"
                              :underline="false"
                              @click.native.prevent="handleClick('conditionMoveUp', index, scope.$index)"
                            >
                              上移
                            </el-link>
                            <el-link
                              v-show="drawerType !== 'view2'"
                              type="primary"
                              :underline="false"
                              @click.native.prevent="handleClick('conditionMoveDown', index, scope.$index)"
                            >
                              下移
                            </el-link>
                          </template>
                        </el-table-column>
                      </el-table>
                      <el-button
                        v-if="drawerType !== 'view'"
                        v-show="drawerType !== 'view2'"
                        type="text"
                        style="padding-left: 14px; margin-top: 3px"
                        icon="el-icon-plus"
                        @click="handleClick('conditionAdd', index)"
                      >
                        添加条件
                      </el-button>
                      <el-form-item v-if="type === 'file'" label="测试结论" prop="testResult" class="testResult">
                        如果满足条件 输出：
                        <span class="success result">通过</span>
                        如果不满足条件 输出：
                        <span class="fail result">不通过</span>
                        不满足条件X:（条件内容）
                        <!-- 不满足条件“{{ item.ruleName }}” -->
                      </el-form-item>
                      <template v-else>
                        <el-form-item label="满足条件" prop="testResult" class="testResult">
                          {{
                            item.type === 1
                              ? item.ruleName.replace(/依赖规则/, '可配置')
                              : item.ruleName.replace(/配置规则/, '配置通过')
                          }}
                        </el-form-item>
                        <el-form-item label="不满足条件" prop="testResult" class="testResult">
                          {{
                            item.type === 1
                              ? item.ruleName.replace(/依赖规则/, '不可配置')
                              : item.ruleName.replace(/配置规则/, '配置不通过')
                          }}
                        </el-form-item>
                      </template>
                    </el-row>
                  </el-form>
                </div>
              </transition-group>
            </el-scrollbar>
          </el-form>
        </div>
        <div class="drawerFooter" align="right">
          <el-button @click="cancelForm">退出页面</el-button>
          <el-button v-if="drawerType === 'edit'" type="primary" @click="submitForm">保存变更</el-button>
          <el-button v-if="drawerType === 'copy'" type="primary" @click="submitForm">保存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { randomString } from '@/utils/index'
import {
  initRuleSet,
  getFactModeOptionList,
  getFactModeAndComparatorToStandardSpecificationOptionList,
  editRuleSet
} from '@/api/rule-management'
import { ConditionalType } from '@/utils/enum/index'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
export default {
  name: 'RuleSetDetail',
  components: {},
  props: {
    type: {
      type: String,
      default: ''
    },
    conditionalRelationOption: {
      type: Array,
      default: () => {
        return []
      }
    },
    variableModelOption: {
      type: Array,
      default: () => {
        return []
      }
    },
    factModeToComparatorOption: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    let self = this
    return {
      ConditionalType: ConditionalType,
      firstLoad: false,
      drawerVisible: false,
      historyFormData: {},
      formData: {
        ruleSetId: null,
        ruleSetName: '',
        parameterModuleIdList: [],
        ruleDataList: []
      },
      conditionContents: {},
      conditionOptions: {},
      drawerType: '',
      formRuleRules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { validator: self.validateRuleName, trigger: 'blur' }
        ],
        conditionalRelation: [{ required: true, message: '请选择条件关系', trigger: ['blur', 'change'] }]
      },
      factModeOption: [],
      factModeObj: {},
      standardSpecificationOption: {},
      initRuleSetRequestId: generateUUID(),
      getFactModeOptionListRequestId: generateUUID(),
      getFactModeAndComparatorToStandardSpecificationOptionListRequestId: generateUUID(),
      editRuleSetRequestId: generateUUID()
    }
  },
  computed: {
    prepositionRuleList() {
      let arr = []
      this.formData.ruleDataList.forEach((item, index) => {
        if (item.ruleName) {
          arr.push({
            label: item.ruleName,
            value: item.ruleId,
            propId: item.propId
          })
        }
      })
      return arr
    }
  },
  watch: {
    'formData.parameterModuleIdList': {
      handler() {
        if (this.drawerType !== 'view') {
          this.getFactModeOption()
        }
      }
      // deep: true
    },
    prepositionRuleList: {
      handler(list) {
        if (this.drawerType !== 'view') {
          let prepositionRulePropIds = list.map((item) => {
            return item.propId
          })
          this.formData.ruleDataList.forEach((item) => {
            if (!prepositionRulePropIds.includes(item.prepositionRuleData.propId)) {
              item.prepositionRuleData = {}
            }
          })
        }
      },
      deep: true
    }
  },
  mounted() {
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.initRuleSetRequestId) {
        let res = e.data.response
        if (res.success) {
          self.transFormData(self.drawerType, res.data)
        } else {
          self.$message.error(res.message)
        }
      } else if (e.data.webInfo.requestId === self.getFactModeOptionListRequestId) {
        self.setFactModeOptionList(e.data.response)
      } else if (
        e.data.webInfo.requestId === self.getFactModeAndComparatorToStandardSpecificationOptionListRequestId
      ) {
        self.setFactModeAndComparatorToStandardSpecificationOptionList(e.data.response)
      } else if (e.data.webInfo.requestId === self.editRuleSetRequestId) {
        let res = e.data.response
        if (res.success) {
          self.afterEditRuleSet(res)
        } else {
          self.$notify.error(res.message)
        }
      }
    },
    is(type, currentRow) {
      this.firstLoad = true
      this.drawerVisible = true
      this.drawerType = type
      if (type === 'view') {
        this.transFormData(type, currentRow)
      } else {
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.initRuleSetRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/ruleSet/init',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { ruleSetId: currentRow.ruleSetId },
            WebInfo: {
              requestId: this.initRuleSetRequestId
            }
          }
          postMessage(message)
        } else {
          initRuleSet({ ruleSetId: currentRow.ruleSetId }).then((res) => {
            this.transFormData(type, res.data)
          })
        }
      }
    },
    transStandardSpecificationOption(data) {
      const addDisabled = (data) => {
        data.forEach((item) => {
          item.disabled = false
          if (item.children) {
            addDisabled(item.children)
          }
        })
      }
      addDisabled(data)
      return data
    },
    transFormData(type, formData) {
      if (type === 'copy') {
        formData.ruleSetId = undefined
      }
      formData.ruleDataList.forEach((item) => {
        item.propId = item.ruleId
        if (type === 'copy') {
          item.ruleId = undefined
        }
        if (type !== 'view' && item.prepositionRuleData.value) {
          item.prepositionRuleData.propId = item.prepositionRuleData.value
        }
        if (this.type === 'file') {
          item.conditionDataList.forEach((row) => {
            if (type === 'copy') {
              row.conditionId = undefined
            }
            row.visible = false
            row.factMode = row.factMode.map((factModeRow) => {
              return Number(factModeRow) == factModeRow ? Number(factModeRow) : factModeRow
            })
            if (row.standardSpecification?.[0] == 1004) {
              row.enterValue = row.standardSpecification[1]
              row.standardSpecification = [1004]
            } else {
              if (row.standardSpecification.length > 0 && [1, 2, 3].includes(row.comparator)) {
                let arr = []
                let arr1 = row.standardSpecification[row.standardSpecification.length - 1].split('@!')
                let index = row.standardSpecification.findIndex((tem) => tem.indexOf(arr1[0] + '@!') == 0)
                if (index != -1) {
                  for (let i = index; i < row.standardSpecification.length; i++) {
                    let tem = []
                    for (let j = 0; j < index; j++) {
                      tem.push(
                        Number(row.standardSpecification[j]) == row.standardSpecification[j]
                          ? Number(row.standardSpecification[j])
                          : row.standardSpecification[j]
                      )
                    }
                    tem.push(row.standardSpecification[i])
                    arr.push(tem)
                  }
                }
                row.standardSpecification = arr
              } else {
                row.standardSpecification = row.standardSpecification.map((standardRow) => {
                  return Number(standardRow) == standardRow ? Number(standardRow) : standardRow
                })
              }
            }
          })
        } else {
          item.conditionDataList.forEach((row) => {
            row.factModeName = '获取"' + row.factMode + '"字段值'
          })
        }
      })
      console.log(formData)
      this.formData = formData
      // console.log(this.formData)
      this.historyFormData = JSON.parse(JSON.stringify(formData))
    },
    transTreeObj(data, obj) {
      data.forEach((item) => {
        obj[item.value] = item
        if (item.children) {
          this.transTreeObj(item.children, obj[item.value])
        }
      })
      return obj
    },
    getFactModeOption() {
      if (this.formData.parameterModuleIdList.length === 0) {
        this.factModeOption = []
        this.factModeObj = {}
        this.formData.ruleDataList.forEach((item) => {
          item.conditionDataList.forEach((row) => {
            row.factMode = []
            row.nearestFactMode = ''
            row.comparator = ''
            row.standardSpecification = []
          })
        })
        this.getFactModeAndComparatorToStandardSpecificationOptionList()
      } else {
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.getFactModeOptionListRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/ruleSet/getFactModeOptionList',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { parameterModuleIdList: this.formData.parameterModuleIdList },
            WebInfo: {
              requestId: this.getFactModeOptionListRequestId
            }
          }
          postMessage(message)
        } else {
          getFactModeOptionList({
            parameterModuleIdList: this.formData.parameterModuleIdList
          }).then((res) => {
            this.setFactModeOptionList(res)
          })
        }
      }
    },
    setFactModeOptionList(res) {
      this.factModeOption = res.data
      this.factModeObj = this.transTreeObj(this.factModeOption, {})

      this.formData.ruleDataList.forEach((item) => {
        item.conditionDataList.forEach((row) => {
          if (row.factMode.length > 0) {
            let obj = this.factModeObj
            let arr = []
            row.factMode.forEach((factModeItem) => {
              obj = obj?.[factModeItem]
              if (obj) arr.push(obj.type + '-' + obj.value)
            })
            if (!obj?.value) {
              row.factMode = []
              row.nearestFactMode = ''
              row.comparator = ''
              row.standardSpecification = []
            } else {
              let len = arr.length
              for (let i = len - 1; i >= 0; i--) {
                if (arr[i].indexOf('1-') != -1) {
                  row.nearestFactMode = arr[i].split('-')[1]
                  break
                }
              }
            }
          } else {
            row.factMode = []
            row.nearestFactMode = ''
            row.comparator = ''
            row.standardSpecification = []
          }
        })
      })
      this.getFactModeAndComparatorToStandardSpecificationOptionList()
    },
    getFactModeAndComparatorToStandardSpecificationOptionList() {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.getFactModeAndComparatorToStandardSpecificationOptionListRequestId = generateUUID()
        let message = {
          RequestUrl:
            process.env.VUE_APP_URL + '/ruleSet/getFactModeAndComparatorToStandardSpecificationOptionList',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: { parameterModuleIdList: this.formData.parameterModuleIdList },
          WebInfo: {
            requestId: this.getFactModeAndComparatorToStandardSpecificationOptionListRequestId
          }
        }
        postMessage(message)
      } else {
        getFactModeAndComparatorToStandardSpecificationOptionList({
          parameterModuleIdList: this.formData.parameterModuleIdList
        }).then((res) => {
          this.setFactModeAndComparatorToStandardSpecificationOptionList(res)
        })
      }
    },
    setFactModeAndComparatorToStandardSpecificationOptionList(res) {
      this.firstLoad = false
      let obj = {}
      let data = res.data
      for (let key in data) {
        obj[key] = this.transStandardSpecificationOption(data[key])
      }
      this.standardSpecificationOption = obj
      this.formData.ruleDataList.forEach((item) => {
        item.conditionDataList.forEach((row) => {
          if (row.factMode.length > 0 && row.comparator) {
            let standardSpecificationOption = this.transTreeObj(
              this.standardSpecificationOption[row.nearestFactMode + '-' + row.comparator] ?? [],
              {}
            )
            if ([1, 2, 3].includes(row.comparator)) {
              let result = true
              row.standardSpecification.every((standard) => {
                let obj = standardSpecificationOption
                standard.forEach((row) => {
                  obj = obj?.[row]
                })
                if (!obj?.value) {
                  result = false
                  return false
                }
                return true
              })
              if (!result) row.standardSpecification = []
            } else {
              let obj = standardSpecificationOption
              row.standardSpecification.forEach((standard) => {
                obj = obj?.[standard]
              })
              if (!obj?.value) {
                row.standardSpecification = []
              }
            }
          }
        })
      })
    },
    handleClick(name, index, conditionIndex) {
      let conditionDataList = []
      if (name.indexOf('condition') != -1) {
        conditionDataList = this.formData.ruleDataList[index].conditionDataList
      }
      switch (name) {
        case 'add':
          this.formData.ruleDataList.push({
            propId: randomString(11),
            ruleName: '',
            ruleRemark: '',
            prepositionRuleData: {},
            conditionalRelation: 1,
            conditionDataList: []
          })
          break
        case 'del':
          this.formData.ruleDataList.splice(index, 1)
          break
        case 'conditionAdd':
          conditionDataList.push({
            visible: false,
            description: '',
            factMode: [],
            comparator: '',
            enterValue: '',
            standardSpecification: []
          })
          break
        case 'conditionDel':
          conditionDataList.splice(conditionIndex, 1)
          break
        case 'conditionCopy':
          conditionDataList.push({ ...conditionDataList[conditionIndex], conditionId: undefined })
          break
        case 'conditionMoveUp':
          if (conditionIndex === 0) return
          this.handlePositionSwap(conditionDataList, conditionIndex - 1, conditionIndex)
          break
        case 'conditionMoveDown':
          if (conditionIndex === conditionDataList.length - 1) return
          this.handlePositionSwap(conditionDataList, conditionIndex, conditionIndex + 1)
          break
      }
    },
    handlePositionSwap(arr, i, j) {
      let obj = JSON.parse(JSON.stringify(arr[i]))
      arr.splice(i, 1, arr[j])
      arr.splice(j, 1, obj)
    },
    handleChangePrepositionRule(val, index) {
      if (val) {
        console.log(this.prepositionRuleList)
        this.prepositionRuleList.every((item) => {
          if (item.propId === val) {
            this.formData.ruleDataList[index].prepositionRuleData.label = item.label
            this.formData.ruleDataList[index].prepositionRuleData.value = item.value
            return false
          }
          return true
        })
      } else {
        this.formData.ruleDataList[index].prepositionRuleData.label = ''
        this.formData.ruleDataList[index].prepositionRuleData.value = undefined
      }
    },
    validateRuleName(rule, value, callback) {
      let count = 0
      this.formData.ruleDataList.forEach((item) => {
        if (item.ruleName === value) {
          count++
        }
      })
      if (count > 1) {
        callback(new Error('规则名称重复'))
      } else {
        callback()
      }
    },
    getPrepositionRuleArr(propId, arr) {
      this.formData.ruleDataList.forEach((item) => {
        if (item.prepositionRuleData.propId === propId) {
          arr.push(item.propId)
          this.getPrepositionRuleArr(item.propId, arr)
        }
      })
      return arr
    },
    // 事实方式
    handleChangeFactMode(val, index, conditionIndex) {
      if (val.length === 0) {
        this.formData.ruleDataList[index].conditionDataList[conditionIndex].nearestFactMode = undefined
        this.formData.ruleDataList[index].conditionDataList[conditionIndex].comparator = undefined
        this.formData.ruleDataList[index].conditionDataList[conditionIndex].standardSpecification = []
      } else {
        let arr = []
        let obj = this.factModeObj
        val.forEach((item) => {
          obj = obj[item]
          arr.push(obj.type + '-' + obj.value)
        })
        let row = this.formData.ruleDataList[index].conditionDataList[conditionIndex]
        let len = arr.length
        for (let i = len - 1; i >= 0; i--) {
          if (arr[i].indexOf('1-') != -1) {
            let nearestFactMode = arr[i].split('-')[1]
            row.nearestFactMode = nearestFactMode
            if (this.factModeToComparatorOption[nearestFactMode]) {
              let comparatorOption = this.factModeToComparatorOption[nearestFactMode].map((item) => {
                return item.value
              })
              if (!comparatorOption.includes(row.comparator)) {
                row.comparator = undefined
                row.standardSpecification = []
              } else {
                this.handleChangeComparator(row.comparator, index, conditionIndex)
              }
            }
            break
          }
        }
      }
    },
    getValueOption(factMode, index) {
      if (!this.factModeObj) {
        return null // 或者返回一个默认值，表示数据未准备好
      }

      if (this.conditionOptions.hasOwnProperty(index)) {
        if (Object.keys(this.conditionOptions[index]).length > 0) {
          return this.conditionOptions[index]
        }
      }
      const parts = []
      let tempObj = JSON.parse(JSON.stringify(this.factModeObj)) // 防止覆写原 JSON

      for (const item of factMode) {
        if (tempObj[item]?.label !== undefined) {
          parts.push(tempObj[item].label)
          tempObj = tempObj[item]
        } else {
          break // 停止循环，因为没有有效的 label
        }
      }

      this.conditionContents[index] = parts

      return this.convertStringToCascaderOptions(parts, index)
    },
    convertStringToCascaderOptions(parts, index) {
      const cascaderOptions = []
      let currentLevel = cascaderOptions

      for (let i = 0; i < parts.length; i++) {
        const part = parts[i]
        const cascaderOption = {
          value: part,
          label: part,
          children: i < parts.length - 1 ? [] : null
        }
        currentLevel.push(cascaderOption)
        currentLevel = cascaderOption.children
      }

      this.conditionOptions[index] = cascaderOptions
      return cascaderOptions
    },

    //
    handleChangeComparator(val, index, conditionIndex) {
      let row = this.formData.ruleDataList[index].conditionDataList[conditionIndex]
      if (val) {
        if (this.standardSpecificationOption[row.nearestFactMode + '-' + row.comparator]) {
          let standardSpecificationOption = this.transTreeObj(
            this.standardSpecificationOption[row.nearestFactMode + '-' + row.comparator] ?? [],
            {}
          )

          if ([1, 2, 3].includes(val)) {
            let result = true
            row.standardSpecification.every((item) => {
              if (Array.isArray(item)) {
                let obj = standardSpecificationOption
                item.forEach((row) => {
                  obj = obj?.[row]
                })
                if (!obj?.value) {
                  result = false
                  return false
                }
                return true
              } else {
                result = false
                return false
              }
            })
            if (!result) row.standardSpecification = []
          } else {
            let obj = standardSpecificationOption
            row.standardSpecification.forEach((item) => {
              obj = obj?.[item]
            })
            if (!obj?.value) {
              row.standardSpecification = []
            }
          }
        }
      } else {
        row.standardSpecification = []
      }
    },
    // 标准规范
    getStandardSpecification(data, val, comparator, visible) {
      let newData = JSON.parse(JSON.stringify(data))
      if (visible) {
        if (val.length > 0 && [1, 2, 3].includes(comparator)) {
          let standardSpecification = [...new Set(val.toString().split(','))]
          const setDisabled = (itemData, level) => {
            level++
            for (let i = 0; i < itemData.length; i++) {
              if (standardSpecification.includes(itemData[i].value.toString()) && level === val[0].length) {
                itemData.forEach((item) => {
                  item.disabled = false
                  // this.$set(item, 'disabled', false)
                  if (item.children) {
                    setDisabled(item.children, level)
                  }
                })

                if (itemData[i].children) {
                  setDisabled(itemData[i].children, level)
                }
                break
              } else {
                itemData[i].disabled = true
                // this.$set(itemData[i], 'disabled', true)
              }
              if (itemData[i].children) {
                setDisabled(itemData[i].children, level)
              }
            }
          }
          setDisabled(newData, 0)
          // console.log(data)
        } else {
          const setDisabled = (itemData) => {
            itemData.forEach((item) => {
              item.disabled = false
              // this.$set(item, 'disabled', false)
              if (item.children) {
                setDisabled(item.children)
              }
            })
          }
          setDisabled(newData)
        }
      }

      return newData
    },
    // 提交表单
    submitForm() {
      // console.log(this.formData)
      let formData = JSON.parse(JSON.stringify(this.formData))
      let validate = true
      formData.ruleDataList.forEach((item, index) => {
        this.$refs['formRuleData' + index][0].validate((valid) => {
          validate = validate && valid
        })
        item.conditionDataList.forEach((row) => {
          if (row.standardSpecification.length > 0 && [1, 2, 3].includes(row.comparator)) {
            // let str = row.standardSpecification[row.standardSpecification.length - 1].split('@!')
            // let pos = row.standardSpecification[0].findIndex((tem) => tem.toString().indexOf(str + '@!') != -1)
            // let standardSpecification = []
            // for (let i = 0; i < pos; i++) {
            //   standardSpecification.push(row.standardSpecification[0][i])
            // }
            // row.standardSpecification.forEach((standard) => {
            //   standardSpecification.push(standard[pos])
            // })
            let standardSpecification = [...new Set(row.standardSpecification.toString().split(','))]
            row.standardSpecification = standardSpecification
          }
          if (row.standardSpecification?.[0] === 1004) {
            row.standardSpecification = [1004, row.enterValue]
          }
        })
      })
      if (!validate) return
      let result = true
      let self = this
      formData.ruleDataList.every((item, index) => {
        item.conditionDataList.every((row, rowIndex) => {
          if (row.factMode.length === 0) {
            result = false
            self.$notify.warning('第' + (index + 1) + '个规则第' + (rowIndex + 1) + '行条件请选择事实方式')
            return false
          }
          if (!row.comparator) {
            result = false
            self.$notify.warning('第' + (index + 1) + '个规则第' + (rowIndex + 1) + '行条件请选择比较符')
            return false
          }
          if (row.standardSpecification.length === 0) {
            result = false
            self.$notify.warning('第' + (index + 1) + '个规则第' + (rowIndex + 1) + '行条件请选择标准规范')
            return false
          } else {
            if (row.standardSpecification?.[0] === 1004 && row.enterValue.indexOf('@!') != -1) {
              result = false
              self.$notify.warning(
                '第' +
                  (index + 1) +
                  '个规则第' +
                  (rowIndex + 1) +
                  '行条件标准规范为选择输入的话，输入值不能包含"@!"'
              )
              return false
            }
          }
          return true
        })
        return result
      })
      if (!result) return
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.editRuleSetRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/ruleSet/edit',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: formData,
          WebInfo: {
            requestId: this.editRuleSetRequestId
          }
        }
        postMessage(message)
      } else {
        editRuleSet(formData).then((res) => {
          this.afterEditRuleSet(res)
        })
      }
    },
    afterEditRuleSet(res) {
      this.$notify.success((this.drawerType === 'edit' ? '保存变更' : '保存') + '成功')
      this.drawerType = 'edit'
      let data = res.data
      this.formData.ruleSetId = data.ruleSetId
      this.formData.ruleDataList.forEach((item, index) => {
        item.ruleId = data.ruleDataList[index].ruleId
        // item.propId = item.ruleId
        item.conditionDataList.forEach((row, rowIndex) => {
          row.conditionId = data.ruleDataList[index].conditionDataList[rowIndex].conditionId
        })
      })
      this.historyFormData = JSON.parse(JSON.stringify(this.formData))
      // this.transFormData('edit', res.data)
      // this.$emit('close')
      // this.drawerVisible = false
    },
    whetherAsk() {
      if (this.drawerType === 'copy' && !this.formData.ruleSetId) {
        return false
      } else {
        // 比较变量库
        if (
          JSON.stringify(this.formData.parameterModuleIdList.sort()) !=
          JSON.stringify(this.historyFormData.parameterModuleIdList.sort())
        ) {
          return true
        }

        // 判断规则
        let ruleDataList = this.formData.ruleDataList
        let historyRuleList = this.historyFormData.ruleDataList
        if (ruleDataList.length === historyRuleList.length) {
          let result = false
          for (let i = 0; i < ruleDataList.length; i++) {
            if (ruleDataList[i].ruleName != historyRuleList[i].ruleName) {
              result = true
              break
            }
            if (ruleDataList[i].ruleRemark != historyRuleList[i].ruleRemark) {
              result = true
              break
            }
            if (ruleDataList[i].prepositionRuleId != historyRuleList[i].prepositionRuleId) {
              result = true
              break
            }
            if (ruleDataList[i].conditionalRelation != historyRuleList[i].conditionalRelation) {
              result = true
              break
            }
            // ruleDataList[i].conditionDataList.forEach((row) => {
            //   if (row.standardSpecification.length > 0 && [1, 2, 3].includes(row.comparator)) {
            //     row.standardSpecification = [...new Set(row.standardSpecification.toString().split(','))]
            //   }
            // })
            if (
              JSON.stringify(
                ruleDataList[i].conditionDataList.map((item) => {
                  return {
                    comparator: item.comparator,
                    conditionId: item.conditionId,
                    description: item.description,
                    factMode: item.factMode,
                    standardSpecification: item.standardSpecification
                  }
                })
              ) !=
              JSON.stringify(
                historyRuleList[i].conditionDataList.map((item) => {
                  return {
                    comparator: item.comparator,
                    conditionId: item.conditionId,
                    description: item.description,
                    factMode: item.factMode,
                    standardSpecification: item.standardSpecification
                  }
                })
              )
            ) {
              result = true
              break
            }
          }
          return result
        } else {
          return true
        }
      }
    },
    // 取消表单
    cancelForm() {
      if (this.drawerType === 'view' || this.drawerType === 'view2') {
        this.$emit('close')
        this.drawerVisible = false
      } else {
        let result = this.whetherAsk()
        if (result) {
          this.$confirm('是否保存变更?', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '保存',
            cancelButtonText: '不保存',
            type: 'warning'
          })
            .then(() => {
              this.submitForm()
            })
            .catch((action) => {
              if (action === 'cancel') {
                this.$emit('close')
                this.drawerVisible = false
              }
            })
        } else {
          this.$emit('close')
          this.drawerVisible = false
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.ruleSetDetail {
  height: 100%;
  /deep/label {
    font-weight: 500;
  }

  .drawerForm {
    display: flex;
    flex-direction: column;
    height: 100%;

    .w360 {
      width: 360px;
    }
    .cascaderView /deep/.el-tag__close {
      display: none;
    }
    .formScrollbar {
      width: calc(100% - 64px);
      overflow-x: auto;
      height: calc(100% - 100px);
      margin: 0px 32px;
    }
    .formContent {
      width: 1278px;
      height: 100%;
      display: flex;
      flex-direction: column;
      .fontBold {
        font-weight: bold;
      }
    }
    .show-word-limit {
      /deep/.el-input__inner {
        padding-right: 45px;
      }
    }
    .show-word-limit-52 {
      /deep/.el-input__inner {
        padding-right: 52px;
      }
    }
    .carryBtn {
      position: absolute;
      right: 24px;
    }
    .ruleSetInfo {
      margin-bottom: 6px;
    }
    .ruleContent {
      flex: 1;
      margin-bottom: 15px;

      .ruleItem:first-of-type {
        border-top: 1px dashed #b9c8dc;
      }
      .ruleItem {
        padding: 24px 0;
        border-bottom: 1px dashed #b9c8dc;
        .ruleBottom {
          background-color: #f5f7fa;
          padding: 24px 10px 6px;
          .conditionTable {
            background-color: #f5f7fa;
            /deep/tr,
            /deep/th,
            /deep/td {
              background-color: #f5f7fa;
              border: none !important;
            }
            /deep/.el-table__fixed::before,
            /deep/.el-table__fixed-right::before {
              background-color: #f5f7fa;
            }
            .el-link + .el-link {
              margin-left: 0;
            }

            .conditionDel {
              padding-left: 0;
            }
          }
          .conditionTable::before {
            background-color: #f5f7fa;
          }
          .conditionContent {
            display: flex;
            align-items: center;
            .treeItem {
              width: 280px;
              background-color: #f5f7fa;
            }
            .comparatorContent {
              padding: 0 10px;
              width: 140px;
              text-align: center;
            }
            .conditionInput {
              margin-right: 10px;
            }
          }
        }

        .testResult {
          margin-top: 6.5px;
          .result {
            border-radius: 12px 12px 12px 12px;
            opacity: 1;
            font-weight: 500;
            color: #ffffff;
            font-size: 12px;
            width: 56px;
            height: 22px;
            line-height: 22px;
            display: inline-block;
            text-align: center;
          }

          .success {
            background: #44ae74;
            // padding: 5px 16px;
            margin-right: 20px;
          }
          .fail {
            background: #ff0000;
            // padding: 5px 10px;
            margin-right: 10px;
          }
        }
      }
    }
  }

  .pageTitle {
    padding: 15px;
    font-size: 16px;
    color: #333;
    font-weight: bold;
    .titleText {
      display: inline;
      padding-right: 20px;
      padding-left: 5px;
    }
  }
  .drawerFooter {
    padding: 0 20px;
    float: right;
  }
}
</style>
<style lang="scss">
// @import '@/styles/element-variables.scss';
.checkStrictlyPopper {
  .el-cascader-panel {
    .el-scrollbar .el-cascader-node:has(.hiddenPrefixIcon) {
      .el-radio,
      .el-checkbox {
        display: none;
      }
      .el-cascader-node__label {
        padding-left: 0;
      }
    }
  }
}

.cascaderView {
  .el-cascader-panel {
    .el-scrollbar {
      .el-checkbox,
      .el-icon-check {
        display: none;
      }
      .el-cascader-node__label {
        padding-left: 0;
      }

      .el-cascader-node.in-active-path,
      .el-cascader-node.is-selectable.in-checked-path,
      .el-cascader-node.is-active {
        color: #606266;
        font-weight: unset;
      }
    }
  }
}
</style>
